import React, {useEffect, useState} from 'react';
import {getStuListApi} from "../api/stuApi";
import {NavLink, useLocation} from "react-router-dom";
import Alert from "./Alert";

function Home(props) {
    const [stuList, setStuList] = useState([])
    const [searchItem, setSearchItem] = useState('')
    const [searchList, setSearchList] = useState([])
    const [alert, setAlert] = useState(null)
    const location = useLocation()
    // 依赖项需要为空，否则将会一直调用 useEffect
    useEffect(() => {
        getStuListApi().then(({data}) => {
            setStuList(data)
        })
    }, []);
    useEffect(() => {
        if (location.state) {
            setAlert(location.state)
        }
    }, [location]);

    const showAlert = alert ? <Alert alert={location.state.alert} type={location.state.type}/> : null
    const handleChange = (value) => {
        setSearchItem(value)
        const arr = stuList.filter(item => {
            return item.name.match(value)
        })
        setSearchList(arr)
    }
    const list = searchItem ? searchList : stuList
    const trs = list.map((item, index) => {
        return (
            <tr key={index}>
                <td>{item.name}</td>
                <td>{item.age}</td>
                <td>{item.phone}</td>
                <td>
                    <NavLink to={`/detail/${item.id}`}>详情</NavLink>
                </td>
            </tr>
        )
    })
    return (
        <div>
            {showAlert}
            <h1>学生列表</h1>
            <input type="text" className="form-control" placeholder="搜搜" value={searchItem}
                   onChange={e => handleChange(e.target.value)}/>
            <table className="table table-striped table-bordered" style={{marginTop: 20, textAlign: "center"}}>
                <thead>
                <tr>
                    <th style={{textAlign: "center"}}>姓名</th>
                    <th style={{textAlign: "center"}}>年龄</th>
                    <th style={{textAlign: "center"}}>联系方式</th>
                    <th style={{textAlign: "center"}}>操作</th>
                </tr>
                </thead>
                <tbody>
                {trs}
                </tbody>
            </table>
        </div>
    );
}

export default Home;